﻿using OneStationFile.IBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;

namespace OneStationFile.WEB.Controllers
{
    public class LoginController : Controller
    {
        protected IBaseService BaseService { get; set; }
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult LoginIn() {
            return View();
        }
        public ActionResult LoginOut() {
            Common.CacheHelper.DeleteCache("users");
            Session.Clear();
            return View("LoginIn");
        }
        public ActionResult ShowValidateCode() {
            Common.ValidateCode ValidateCode = new OneStationFile.Common.ValidateCode();

            string code = ValidateCode.CreateValidateCode(4);//生成验证码，传几就是几位验证码
            Session["code"] = code;
            byte[] buffer = ValidateCode.CreateValidateGraphic(code);//把验证码画到画布
            return File(buffer, "image/jpeg");
        }
        [HttpPost]
        public JsonResult LoginHandle(string name,string pwd,string codes) {
            
            var result = new { msg = "登录成功!", res = true };
            object codeSession = Session["code"];
            if (codeSession == null)
            {
                result = new { msg = "验证码错误!", res = false };
                return Json(result);
            }
            if (codeSession.ToString() != codes)
            {
                result = new { msg = "验证码错误!", res = false };
                return Json(result);
            }
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd))
            {
                result = new { msg = "用户名或密码为空!", res = false };
                return Json(result);
            }
            Model.Users users = BaseService.GetModelByWhere<Model.Users>(p => p.Name == name && p.Pwd == pwd);
            if (users == null)
            {
                result = new { msg = "用户名或密码错误!", res = false };
                return Json(result);
            }
            Common.CacheHelper.SetCache("users", users);
            return Json(result);
        }
    }
}